﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace WpfApplication1
{
    class Http
    {
        public static string GetCookie(string strUrl, ref string strCookie)
        {
            //strUrl = "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=false";
            //strUrl = "https://passport.baidu.com/v2/api/?getapi&tpl=ik&apiver=v3&tt=&class=login&callback=bd__cbs__kfb12k";
            //strUrl = "http://zhidao.baidu.com";
            //strUrl = "http://www.baidu.com";

            WebRequest webRequest;
            webRequest = WebRequest.Create(strUrl);
            webRequest.Credentials = CredentialCache.DefaultCredentials;

            WebResponse webResponse;
            webResponse = webRequest.GetResponse();

            string html = new StreamReader(webResponse.GetResponseStream(), Encoding.Default).ReadToEnd();
            strCookie = webResponse.Headers.Get("Set-Cookie");
            //strCookie = strCookie.Split(';')[0];
            //System.Console.WriteLine("获得的Cookie：" + strCookie);
            return html;
        }
        
        public static string GetToken(string strTokenUrl, CookieContainer cookieCon)
        {
            HttpWebRequest webRequest;
            HttpWebResponse webResponse;

            string strUrl = strTokenUrl; // "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true";
            //strUrl = "https://passport.baidu.com/v2/api/?getapi&tpl=ik&apiver=v3&tt=&class=login&callback=bd__cbs__kfb12k";
            //strUrl = "http://www.baidu.com";

            webRequest = (HttpWebRequest)WebRequest.Create(strUrl);
            webRequest.CookieContainer = cookieCon;
                        
            //webRequest.Accept = "*/*";
            //webRequest.Referer = "http://zhidao.baidu.com";
            //webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)";
            webRequest.Method = "GET";
            //webRequest.KeepAlive = true;

            webResponse = (HttpWebResponse)webRequest.GetResponse();
            string strHeader = webResponse.Headers.ToString();
            string strHeaderRequest = webRequest.Headers.ToString();
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);
            string content = streamReader.ReadToEnd();
            string [] strConList = content.Split(';');
            const int iTokenLen = 32;
            for (int i = 0; i < strConList.Length; i++)
            {
                string strCon = strConList[i];
                if ( strCon.IndexOf("login_token") >0 )
                {
                    content = strCon.Split('=')[1];
                    content= content.Trim('\'');
                    int ilen = content.Length;
                    if (iTokenLen == ilen)
                        return content;
                    else
                        return "";
                }
            }
            return content;
        }

        public static string Post(string strPostData, string strPostUrl, CookieContainer cookieCon)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] bin = encoding.GetBytes(strPostData);
            
            HttpWebRequest webRequest;
            HttpWebResponse webResponse;

            webRequest = (HttpWebRequest)HttpWebRequest.Create(strPostUrl);
            webRequest.CookieContainer = cookieCon;

            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Accept = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
            webRequest.Referer = "http://www.baidu.com/cache/user/html/login-1.2.html";
            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)";
            webRequest.Method = "POST";
            webRequest.ContentLength = bin.Length;
            webRequest.KeepAlive = true;
            
            Stream stream;
            stream = webRequest.GetRequestStream();
            stream.Write(bin, 0, bin.Length);
            stream.Close();
            webResponse = (HttpWebResponse)webRequest.GetResponse();
            string strHeader = webResponse.Headers.ToString();
            Stream responseStream = webResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);
            string content = streamReader.ReadToEnd();
            return content;
        }

        public static bool LoginBaidu(string strUser, string strPwd)
        {
            string strUrl = "http://www.baidu.com";
            string strCookie = "";

            GetCookie(strUrl, ref strCookie);

            CookieContainer cookieContainer = new CookieContainer();
            cookieContainer.SetCookies(new Uri(strUrl), strCookie);

            string strTokenUrl = "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true";
            string strToken = GetToken(strTokenUrl, cookieContainer);
            if (strToken == null)
            {
                return false;
            }

            string strPostData = "staticpage=http://www.baidu.com/cache/user/html/jump.html" +
                "&charset=utf-8&token="+strToken + "&tpl=mn&apiver=v3&tt=1364192386768&codestring="+
                "&isPhone=false&safeflg=0&u=http%3A%2F%2Fzhidao.baidu.com%2F" + 
                "&username=" + strUser+"&password=" + strPwd + 
                "&verifycode=&mem_pass=on&ppui_logintime=&callback=parent.bd__pcbs__67fxj7";

            strPostData = "ppui_logintime=&charset=utf-8&codestring=" +
                "&token=" + strToken + "&isPhone=false" +
                "&index=0&u=&safeflg=0" +
                "&staticpage=http://www.baidu.com/cache/user/html/jump.html" +
                "&loginType=1&tpl=mn&callback=parent.bdPass.api.login._postCallback" +
                "&username="+strUser+"&password="+strPwd+ 
                "&verifycode=&mem_pass=on";
            
            string strPostUrl = "https://passport.baidu.com/v2/api/?login";
            string html = Http.Post(strPostData, strPostUrl, cookieContainer);
            return false;
        }
    }
}
